package com.gpscookie.mobile;

import java.io.UnsupportedEncodingException;
import java.util.Random;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import de.enough.polish.ui.Alert;
import de.enough.polish.ui.AlertType;
import de.enough.polish.ui.Display;
import de.enough.polish.ui.Displayable;
import de.enough.polish.util.Locale;

// C:\Java_ME_platform_SDK_3.0\bin\emulator.exe -Xdescriptor:D:\myhobby\wkspc\GPSCookiePolish\dist\Generic-Midp2Cldc11-zh.jad
public class GPSCookie extends MIDlet
{
	private Display display;

	public static RMSStore rmsstore = null;
	public static MainScreen mainScreen = null;
	public static ResultScreen searchScreen = null;
	public static ImageScreen imageScreen = null;
	public static OptionScreen optionScreen = null;
	public static CreateScreen createScreen = null;
	public static ViewScreen viewScreen = null;
	public static FollowScreen followScreen = null;
	public static ForumListScreen forumListScreen = null;
	public static ForumPostScreen forumPostScreen = null;

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		this.rmsstore.close();
	}


	protected void pauseApp() {
		// TODO Auto-generated method stub
		
	}


	protected void startApp() throws MIDletStateChangeException {		
		this.display = Display.getDisplay(this);

		if (this.optionScreen == null) {
			this.optionScreen = new OptionScreen(Locale.get("APPNAME"), this);
		}
		this.rmsstore = new RMSStore();
		this.rmsstore.setMemoryStore(this.optionScreen);
		this.rmsstore.loadMemoryStore();
		
		this.mainScreen = new MainScreen(Locale.get("APPNAME"), this);
		this.setScreen(this.mainScreen);
		
		this.optionScreen.setParent();
	}
	
	public void setScreen(Displayable screen) {
		if (this.display != null && screen != null) {
			this.display.setCurrent(screen);	
		}
	}	
	
	public void search(String url) {
		if (this.searchScreen == null) {
			this.searchScreen = new ResultScreen(Locale.get("APPNAME"), this);
		}
		this.searchScreen.search(url);
		this.display.setCurrent(this.searchScreen);
	}
	
	public void viewMission(String uuid) {
		if (this.viewScreen == null) {
			this.viewScreen = new ViewScreen(Locale.get("APPNAME"), this);
		}
		this.display.setCurrent(this.viewScreen);
		this.viewScreen.download("http://gpscookie.appspot.com/mission/rest/view?uuid="+uuid);
	}
	
	public void showImage(String url) {
		if (this.imageScreen == null) {
			this.imageScreen = new ImageScreen(Locale.get("APPNAME"), this);
		}
		this.display.setCurrent(this.imageScreen);
		String size = String.valueOf(this.imageScreen.getWidth())+"x"+String.valueOf(this.imageScreen.getHeight());		
		this.imageScreen.download("http://ditu.google.cn/staticmap?size="+size+"&maptype=mobile&markers="+url+"&key=ABQIAAAA3Jctzi6h9XjhBnp3WNhIJxQnE-HqWLobAj7gM0G2Up4_rw7kTBTHMO63dhhpN2Rp5h6NYa--6XHbWw&sensor=false&format=png8");
	}
	
	public void settings() {
		if (this.optionScreen == null) {
			this.optionScreen = new OptionScreen(Locale.get("APPNAME"), this);
		}
		this.display.setCurrent(optionScreen);
	}
	
	public void follow(JSONObject mission) {
		if (this.followScreen == null) {
			this.followScreen = new FollowScreen(Locale.get("APPNAME"), this);
		}
		try {
			this.followScreen.setMission(mission);
		} catch (JSONException e) {
		}
		this.display.setCurrent(this.followScreen);
	}
	
	public void create() {
		if (this.createScreen == null) {
			this.createScreen = new CreateScreen(Locale.get("APPNAME"), this);
		}
		if (rmsstore.get(RMSStore.USER, "").length()==0) {
			if (this.optionScreen == null) {
				this.optionScreen = new OptionScreen(Locale.get("APPNAME"), this);
			}
			this.optionScreen.setInfo(Locale.get("ERROR_NEED_REGISTER"));
			this.display.setCurrent(this.optionScreen);
		} else {		
			this.display.setCurrent(this.createScreen);
		}
	}
	
	public static String string2http(String data)
	throws UnsupportedEncodingException
	{
		if (data == null) {
			return null;
		}		
		byte[] text = data.getBytes("utf-8");
		StringBuffer StrUrl = new StringBuffer();
	    for (int i = 0; i < text.length; ++i) {
	      switch (text[i]) {
	        case ' ':
	          StrUrl.append("%20");
	          break;
	        case '+':
	          StrUrl.append("%2b");
	          break;
	        case '\'':
	          StrUrl.append("%27");
	          break;
	        case '/':
	          StrUrl.append("%2F");
	          break;
	        case '.':
	          StrUrl.append("%2E");
	          break;
	        case '<':
	          StrUrl.append("%3c");
	          break;
	        case '>':
	          StrUrl.append("%3e");
	          break;
	        case '#':
	          StrUrl.append("%23");
	          break;
	        case '%':
	          StrUrl.append("%25");
	          break;
	        case '&':
	          StrUrl.append("%26");
	          break;
	        case '{':
	          StrUrl.append("%7b");
	          break;
	        case '}':
	          StrUrl.append("%7d");
	          break;
	        case '\\':
	          StrUrl.append("%5c");
	          break;
	        case '^':
	          StrUrl.append("%5e");
	          break;
	        case '~':
	          StrUrl.append("%73");
	          break;
	        case '[':
	          StrUrl.append("%5b");
	          break;
	        case ']':
	          StrUrl.append("%5d");
	          break;
	        default:
	        	char ch= (char)(text[i]&0x00ff);
	        	if (ch > 127) {	        		
	        		StrUrl.append("%"+Integer.toHexString(ch));
	        	} else {
	        		StrUrl.append(ch);
	        	}
	          break;
	      }
	    }
	    return StrUrl.toString();		
	}
	
	public static String http2String(byte[] data)
		throws UnsupportedEncodingException
	{
		StringBuffer output = new StringBuffer();
		if (data==null) {
			return null;
		}
		for (int i=0; i<data.length; i++) {
			if (data[i]==92 && i<data.length-5 && data[i+1]==117) {
				byte[] tmp = {data[i+2], data[i+3], data[i+4], data[i+5]};
				String unicode = new String(tmp, "utf-8");
				int chinese = Integer.parseInt(unicode, 16);
				output.append((char)chinese);
				i+=5;
			} else {
				if (data[i]==92) {
					// ignore \
				} else {
					output.append((char)data[i]);
				}
			}
		}
		return output.toString();
	}
	
	public static void setAdItems(JSONArray items)
	{
		String adItem;
		if (items == null || items.length()<=0) {
			adItem = Locale.get("AD");		
		} else {
			int index = new Random().nextInt();
			index = index % items.length();
			try {
				adItem = items.getJSONObject(index).getString("display");
			} catch (JSONException e) {
				adItem =  Locale.get("AD");
			}
		}
		rmsstore.put(RMSStore.AD, adItem);
	}
	
	public static String getOneAd() {		
		return rmsstore.get(RMSStore.AD, Locale.get("AD"));
	}


	public void forumList(JSONObject mission, String secret) {
		if (this.forumListScreen == null) {
			this.forumListScreen = new ForumListScreen(Locale.get("APPNAME"), this);
		}
		try {
			this.forumListScreen.setMission(mission, secret);
		} catch (JSONException e) { }
		this.display.setCurrent(this.forumListScreen);		
	}
	
	public void forumPost(JSONObject mission, String secret) {
		if (rmsstore.get(RMSStore.USER, "").length()==0) {
			if (this.optionScreen == null) {
				this.optionScreen = new OptionScreen(Locale.get("APPNAME"), this);
			}
			this.optionScreen.setInfo(Locale.get("ERROR_NEED_REGISTER"));
			this.display.setCurrent(this.optionScreen);
		} else {
			if (this.forumPostScreen == null) {
				this.forumPostScreen = new ForumPostScreen(Locale.get("APPNAME"), this);
			}
			this.forumPostScreen.setMission(mission, secret);
			this.display.setCurrent(this.forumPostScreen);
		}
	}
}
